<!DOCTYPE html>

<!--
Copyright 2014 Intel Corporation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<html>
<head>
    <title>WebRTC Sample</title>
</head>
<body onload="start()" onunload="stop()">
    <span id="outputtext"></span>
    <span id="debugText"></span>
    <hr />
    <textarea id="inputtext" style="width:100%" onkeypress="onUserKeyPressEvent(event)"></textarea>
    <script type="text/javascript">
        var connection = null;
        var datachannel = null;
        var configuration = { "iceServers": [/*{{{ICESERVERS}}}*/] };
        var currentoffer = null;
        var requester;
        var sdp = "";
        var outputtextbox = document.getElementById("outputtext");
        var inputtextbox = document.getElementById("inputtext");
        var debugtextbox = document.getElementById("debugText");
        var startTime = null;
        var bytesReceived = 0;
        var totalReceived = 0;
        function stop() { connection.close(); }

        function start() {
            msg("Starting...");

            if (typeof mozRTCPeerConnection !== 'undefined') { connection = new mozRTCPeerConnection(configuration); }
            else if (typeof RTCPeerConnection !== 'undefined') { connection = new RTCPeerConnection(configuration); }
            else if (typeof webkitRTCPeerConnection !== 'undefined') { connection = new webkitRTCPeerConnection(configuration); }
            else return false;

            datachannel = connection.createDataChannel("sampleDataChannel", { reliable: true });
            datachannel.onmessage = function (event) { msg("Remote [" + event.currentTarget.label + "]: " + event.data); }
            datachannel.onopen = function () { msg("Local Data channel creation [sampleDataChannel] was successful"); };
            datachannel.onclose = function (event) { msg("Channel [" + event.currentTarget.label + "] was closed by remote"); }

            connection.ondatachannel = onNewDataChannel;
            connection.onicecandidate = onIceCandidate;
            connection.createOffer(onOfferDone, onError, { mandatory: { OfferToReceiveAudio: false, OfferToReceiveVideo: false } });
            connection.oniceconnectionstatechange = function ()
            {
                if (connection.iceConnectionState == 'disconnected') {
                    msg('DISCONNECTED');
                    //alert('This session has closed!');
                    //window.close();
                }
            }
        }

        function onNewDataChannel(e) {
            msg("Channel [" + e.channel.label + "] created by remote peer");
            datachannel = e.channel;
            datachannel.onmessage = onMessage;
            datachannel.onclose = function (event) { msg("Channel [" + event.currentTarget.label + "] was closed by remote"); }
        }

        function onMessage(event)
        {
            if (event.currentTarget.label != "DebugChannel") {
                msg("Remote [" + event.currentTarget.label + "]: " + event.data);
            }
            else
            {
                if (startTime == null)
                {
                    startTime = Date.now();
                }
                else if (Date.now() > (startTime + 10000))
                {
                    startTime = Date.now();
                    bytesReceived = 0;
                }

                bytesReceived += event.data.byteLength;
                totalReceived += event.data.byteLength;

                var rate = 1000 * (bytesReceived / (Date.now() - startTime));
                rate = rate / 1024;
                dbgMsg("Received " + totalReceived/1024 + " Kb @ " + rate.toFixed(2) + " Kbytes per second");
                              
            }
        }

        function onUserKeyPressEvent(event) {
            if (event.keyCode == 13) {
                datachannel.send(inputtextbox.value);
                msg("Local: " + inputtextbox.value);
                inputtextbox.value = "";
                if (e.preventDefault) e.preventDefault();
                if (e.stopPropagation) e.stopPropagation();
                return false;
            }
        }

        function onIceCandidate(e) {
            if (e.candidate == null) {
                msg('Posting WebRTC offer...');
                requester = new XMLHttpRequest();
                requester.onload = initiatorResponse;
                requester.onerror = initiatorErrorResponse;
                requester.open("POST", "http://{{{OFFER_URL}}}", true);
                requester.send(sdp);
                return;
            }
            currentoffer.sdp += ("a=" + e.candidate.candidate + "\r\n");
            sdp = currentoffer.sdp;
        }

        function onCandidateAdded(e) { debug('onCandidateAdded: ' + e); }

        function onOfferDone(offer) {
            // debug(offer.sdp);
            currentoffer = offer;
            connection.setLocalDescription(offer, onSetLocalDescriptionDone, onError);
        }

        function onSetLocalDescriptionDone() { }

        function initiatorResponse() {
            msg('Got answer, connecting...');
            var ax;
            if (typeof mozRTCSessionDescription !== 'undefined') { ax = new mozRTCSessionDescription({ type: "answer", sdp: requester.responseText }) } else { ax = new RTCSessionDescription({ type: "answer", sdp: requester.responseText }) }
            connection.setRemoteDescription(ax, onSetRemoteDescriptionDone, onError);
        }

        function initiatorErrorResponse() { msg('Could not contact server.'); }

        function onSetRemoteDescriptionDone() { debug('setRemoteDescription() completed'); }
        function stop() { connection.close(); }
        function onError(e) { if (e.message) alert("onError: " + e.message); else alert(e); }
        function debug(m) { /* console.log(m); */ }
        function msg(m) { outputtextbox.innerHTML += (m + "<br />"); }
        function dbgMsg(m) { debugtextbox.innerHTML = m; }
    </script>
</body>
</html>